The window object represents an open window in a browser.
If a document contain frames (<iframe> tags), the browser creates one window object for the HTML document, and one additional window object for each frame.
Note: There is no public standard that applies to the Window object, but all major browsers support it.
Property | Description |
---|---|
closed | Returns a Boolean value indicating whether a window has been closed or not |
defaultStatus | Sets or returns the default text in the statusbar of a window |
document | Returns the Document object for the window (See Document object) |
frameElement | Returns the <iframe> element in which the current window is inserted |
frames | Returns all <iframe> elements in the current window |
history | Returns the History object for the window (See History object) |
innerHeight | Returns the inner height of a window's content area |
innerWidth | Returns the inner width of a window's content area |
length | Returns the number of <iframe> elements in the current window |
localStorage | Allows to save key/value pairs in a web browser. Stores the data with no expiration date |
location | Returns the Location object for the window (See Location object) |
name | Sets or returns the name of a window |
navigator | Returns the Navigator object for the window (See Navigator object) |
opener | Returns a reference to the window that created the window |
outerHeight | Returns the outer height of a window, including toolbars/scrollbars |
outerWidth | Returns the outer width of a window, including toolbars/scrollbars |
pageXOffset | Returns the pixels the current document has been scrolled (horizontally) from the upper left corner of the window |
pageYOffset | Returns the pixels the current document has been scrolled (vertically) from the upper left corner of the window |
parent | Returns the parent window of the current window |
screen | Returns the Screen object for the window (See Screen object) |
screenLeft | Returns the horizontal coordinate of the window relative to the screen |
screenTop | Returns the vertical coordinate of the window relative to the screen |
screenX | Returns the horizontal coordinate of the window relative to the screen |
screenY | Returns the vertical coordinate of the window relative to the screen |
sessionStorage | Allows to save key/value pairs in a web browser. Stores the data for one session |
scrollX | An alias of pageXOffset |
scrollY | An alias of pageYOffset |
self | Returns the current window |
status | Sets or returns the text in the statusbar of a window |
top | Returns the topmost browser window |
Method | Description |
---|---|
alert() | Displays an alert box with a message and an OK button |
atob() | Decodes a base-64 encoded string |
blur() | Removes focus from the current window |
btoa() | Encodes a string in base-64 |
clearInterval() | Clears a timer set with setInterval() |
clearTimeout() | Clears a timer set with setTimeout() |
close() | Closes the current window |
confirm() | Displays a dialog box with a message and an OK and a Cancel button |
focus() | Sets focus to the current window |
getComputedStyle() | Gets the current computed CSS styles applied to an element |
getSelection() | Returns a Selection object representing the range of text selected by the user |
matchMedia() | Returns a MediaQueryList object representing the specified CSS media query string |
moveBy() | Moves a window relative to its current position |
moveTo() | Moves a window to the specified position |
open() | Opens a new browser window |
print() | Prints the content of the current window |
prompt() | Displays a dialog box that prompts the visitor for input |
resizeBy() | Resizes the window by the specified pixels |
resizeTo() | Resizes the window to the specified width and height |
scroll() | Deprecated. This method has been replaced by the scrollTo() method. |
scrollBy() | Scrolls the document by the specified number of pixels |
scrollTo() | Scrolls the document to the specified coordinates |
setInterval() | Calls a function or evaluates an expression at specified intervals (in milliseconds) |
setTimeout() | Calls a function or evaluates an expression after a specified number of milliseconds |
stop() | Stops the window from loading |
In the HTML DOM (Document Object Model), everything is a node:
In the HTML DOM, the Element object represents an HTML element.
Element objects can have child nodes of type element nodes, text nodes, or comment nodes.
A NodeList object represents a list of nodes, like an HTML element's collection of child nodes.
Elements can also have attributes. Attributes are attribute nodes (See next chapter).
The following properties and methods can be used on all HTML elements:
Property / Method | Description |
---|---|
element.accessKey | Sets or returns the accesskey attribute of an element |
element.addEventListener() | Attaches an event handler to the specified element |
element.appendChild() | Adds a new child node, to an element, as the last child node |
element.attributes | Returns a NamedNodeMap of an element's attributes |
element.blur() | Removes focus from an element |
element.childElementCount | Returns the number of child elements an element has |
element.childNodes | Returns a collection of an element's child nodes (including text and comment nodes) |
element.children | Returns a collection of an element's child element (excluding text and comment nodes) |
element.classList | Returns the class name(s) of an element |
element.className | Sets or returns the value of the class attribute of an element |
element.click() | Simulates a mouse-click on an element |
element.clientHeight | Returns the height of an element, including padding |
element.clientLeft | Returns the width of the left border of an element |
element.clientTop | Returns the width of the top border of an element |
element.clientWidth | Returns the width of an element, including padding |
element.cloneNode() | Clones an element |
element.compareDocumentPosition() | Compares the document position of two elements |
element.contains() | Returns true if a node is a descendant of a node, otherwise false |
element.contentEditable | Sets or returns whether the content of an element is editable or not |
element.dir | Sets or returns the value of the dir attribute of an element |
element.firstChild | Returns the first child node of an element |
element.firstElementChild | Returns the first child element of an element |
element.focus() | Gives focus to an element |
element.getAttribute() | Returns the specified attribute value of an element node |
element.getAttributeNode() | Returns the specified attribute node |
element.getElementsByClassName() | Returns a collection of all child elements with the specified class name |
element.getElementsByTagName() | Returns a collection of all child elements with the specified tag name |
element.getFeature() | Returns an object which implements the APIs of a specified feature |
element.hasAttribute() | Returns true if an element has the specified attribute, otherwise false |
element.hasAttributes() | Returns true if an element has any attributes, otherwise false |
element.hasChildNodes() | Returns true if an element has any child nodes, otherwise false |
element.id | Sets or returns the value of the id attribute of an element |
element.innerHTML | Sets or returns the content of an element |
element.insertBefore() | Inserts a new child node before a specified, existing, child node |
element.isContentEditable | Returns true if the content of an element is editable, otherwise false |
element.isDefaultNamespace() | Returns true if a specified namespaceURI is the default, otherwise false |
element.isEqualNode() | Checks if two elements are equal |
element.isSameNode() | Checks if two elements are the same node |
element.isSupported() | Returns true if a specified feature is supported on the element |
element.lang | Sets or returns the value of the lang attribute of an element |
element.lastChild | Returns the last child node of an element |
element.lastElementChild | Returns the last child element of an element |
element.namespaceURI | Returns the namespace URI of an element |
element.nextSibling | Returns the next node at the same node tree level |
element.nextElementSibling | Returns the next element at the same node tree level |
element.nodeName | Returns the name of a node |
element.nodeType | Returns the node type of a node |
element.nodeValue | Sets or returns the value of a node |
element.normalize() | Joins adjacent text nodes and removes empty text nodes in an element |
element.offsetHeight | Returns the height of an element, including padding, border and scrollbar |
element.offsetWidth | Returns the width of an element, including padding, border and scrollbar |
element.offsetLeft | Returns the horizontal offset position of an element |
element.offsetParent | Returns the offset container of an element |
element.offsetTop | Returns the vertical offset position of an element |
element.ownerDocument | Returns the root element (document object) for an element |
element.parentNode | Returns the parent node of an element |
element.parentElement | Returns the parent element node of an element |
element.previousSibling | Returns the previous node at the same node tree level |
element.previousElementSibling | Returns the previous element at the same node tree level |
element.querySelector() | Returns the first child element that matches a specified CSS selector(s) of an element |
element.querySelectorAll() | Returns all child elements that matches a specified CSS selector(s) of an element |
element.removeAttribute() | Removes a specified attribute from an element |
element.removeAttributeNode() | Removes a specified attribute node, and returns the removed node |
element.removeChild() | Removes a child node from an element |
element.removeEventListener() | Removes an event handler that has been attached with the addEventListener() method |
element.replaceChild() | Replaces a child node in an element |
element.scrollHeight | Returns the entire height of an element, including padding |
element.scrollIntoView() | Scrolls the specified element into the visible area of the browser window |
element.scrollLeft | Sets or returns the number of pixels an element's content is scrolled horizontally |
element.scrollTop | Sets or returns the number of pixels an element's content is scrolled vertically |
element.scrollWidth | Returns the entire width of an element, including padding |
element.setAttribute() | Sets or changes the specified attribute, to the specified value |
element.setAttributeNode() | Sets or changes the specified attribute node |
element.style | Sets or returns the value of the style attribute of an element |
element.tabIndex | Sets or returns the value of the tabindex attribute of an element |
element.tagName | Returns the tag name of an element |
element.textContent | Sets or returns the textual content of a node and its descendants |
element.title | Sets or returns the value of the title attribute of an element |
element.toString() | Converts an element to a string |
nodelist.item() | Returns the node at the specified index in a NodeList |
nodelist.length | Returns the number of nodes in a NodeList |
Get the number of pixels the content of a <div> element is scrolled horizontally and vertically:
var elmnt = document.getElementById("myDIV");
var x = elmnt.scrollLeft;
var y = elmnt.scrollTop;
Try it Yourself »
More "Try it Yourself" examples below.
The scrollTop property sets or returns the number of pixels an element's content is scrolled vertically.
Tip: Use the scrollLeft property to set or return the number of pixels an element's content is scrolled horizontally.
Tip: To add scrollbars to an element, use the CSS overflow property.
Tip: The onscroll event occurs when an element's scrollbar is being scrolled.
Return the scrollTop property:
element.scrollTop
Set the scrollTop property:
element.scrollTop = pixels
Value | Description |
---|---|
pixels |
Specifies the number of pixels the element's content is scrolled vertically. Special notes:
|
Return Value: | A Number, representing the number of pixels that the element's content has been scrolled vertically |
---|
Scroll the contents of a <div> element TO 50 pixels horizontally and 10 pixels vertically:
var elmnt = document.getElementById("myDIV");
elmnt.scrollLeft = 50;
elmnt.scrollTop = 10;
Try it Yourself »
Scroll the contents of a <div> element BY 50 pixels horizontally and 10 pixels vertically:
var elmnt = document.getElementById("myDIV");
elmnt.scrollLeft += 50;
elmnt.scrollTop += 10;
Try it Yourself »
Scroll the contents of <body> by 30 pixels horizontally and 10 pixels vertically:
var body = document.body; // Safari
var html = document.documentElement; //
Chrome, Firefox, IE and Opera places the overflow at the <html> level, unless else is specified. Therefore, we use the
documentElement property for these browsers
body.scrollLeft += 30;
body.scrollTop += 10;
html.scrollLeft += 30;
html.scrollTop += 10;
Try it Yourself »
Toggle between class names on different scroll positions - When the user scrolls down 50 pixels from the top of the page, the class name "test" will be added to an element (and removed when scrolled up again).
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
Try it Yourself »
Slide in an element when the user has scrolled down 350 pixels from the top of the page (add the slideUp class):
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
document.getElementById("myImg").className = "slideUp";
}
Try it Yourself »
Draw a triangle on scroll:
<!-- Use SVG to draw the triangle (has to be <path>) -->
<svg id="mySVG">
<path fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z">
</svg>
<script>
// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("triangle");
var length = triangle.getTotalLength();
// The start position of the drawing
triangle.style.strokeDasharray = length;
// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
triangle.style.strokeDashoffset = length;
// Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
window.addEventListener("scroll", myFunction);
function myFunction() {
var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
var draw = length * scrollpercent;
// Reverse the drawing (when scrolling upwards)
triangle.style.strokeDashoffset = length - draw;
}
</script>
Try it Yourself »
Scroll the document to the horizontal position "500":
window.scrollTo(500, 0);
Try it Yourself »
More "Try it Yourself" examples below.
The scrollTo() method scrolls the document to the specified coordinates.
Tip: Use the scrollBy() method to scroll a specified distance multiple times.
window.scrollTo(xpos, ypos)
Parameter | Type | Description |
---|---|---|
xpos | Number | Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels |
ypos | Number | Required. The coordinate to scroll to, along the y-axis (vertical), in pixels |
Return Value: | No return value |
---|
Scroll the document to position "300" horizontally and "500" vertically:
window.scrollTo(300, 500);
Try it Yourself »
Scroll the document by 100px horizontally:
window.scrollBy(100, 0); // Scroll 100px to the right
Try it Yourself »
More "Try it Yourself" examples below.
The scrollBy() method scrolls the document by the specified number of pixels.
Note: For this method to work, the visible property of the window's scrollbar must be set to true!
window.scrollBy(xnum, ynum)
Parameter | Type | Description |
---|---|---|
xnum | Number | Required. How many pixels to scroll by, along the x-axis (horizontal). Positive values will scroll to the right, while negative values will scroll to the left |
ynum | Number | Required. How many pixels to scroll by, along the y-axis (vertical). Positive values will scroll down, while negative values scroll up |
Return Value: | No return value |
---|
Scroll the document by 100px vertically:
window.scrollBy(0, 100); // Scroll 100px downwards
Try it Yourself »
Scroll the document horizontally and vertically:
<button onclick="scrollWin(0, 50)">Scroll down</button>
<button onclick="scrollWin(0, -50)">Scroll up</button>
<button onclick="scrollWin(100, 0)">Scroll right</button>
<button onclick="scrollWin(-100, 0)">Scroll left</button>
<script>
function scrollWin(x, y) {
window.scrollBy(x, y);
}
</script>
Try it Yourself »